package com.tp.service;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tp.base.BaseService;
import com.tp.base.Paginator;
import com.tp.model.sys.SysMenu;
import com.tp.model.sys.SysRoleMenu;
import com.tp.model.sys.SysUser;
import com.tp.model.sys.SysUserRole;
import com.tp.utils.SQLUtils;
import com.tp.utils.StrUtils;

import javolution.util.FastList;
import javolution.util.FastMap;

/**
 * 菜单service
 * 
 * @author TP
 *
 */
public class MenuService extends BaseService {

	private static SysMenu sm = new SysMenu().dao();

	/**
	 * 分页查询
	 * 
	 * @param model
	 * @param orderBy
	 * @param paginator
	 * @return
	 */
	public Page<SysMenu> getPageByWhere(SysMenu model, String orderBy, Paginator paginator) {
		SQLUtils sql = new SQLUtils("from " + SysMenu.tableName + " t left join " + SysMenu.tableName
				+ " d on d.id = t.parent_id where 1=1 ");
		if (model.getAttrValues().length != 0) {
			sql.setAlias("t");
			// 查询条件
			sql.whereLike("name", model.getStr("name"));
		}
		// 排序
		if (StrUtils.isEmpty(orderBy)) {
			sql.append(" order by t.sort,t.id desc");
		} else {
			sql.append(" order by t.").append(orderBy);
		}
		Page<SysMenu> page = sm.paginate(paginator, "select t.*,ifnull(d.name,'根目录') as parentname ", sql.toString());
		return page;
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	public boolean deleteObject(String[] ids, Integer uid) {
		if (!StrUtils.empty(ids)) {
			boolean flag = false;
			for (String id : ids) {
				SysMenu model = new SysMenu();
				model.put("update_id", uid);
				flag = model.deleteById(id);
				if (flag) {
					// 删除菜单的时候直接级联移除角色关联的菜单
					Db.update("delete from " + SysRoleMenu.tableName + " where menu_id = ?", id);
				} else {
					break;
				}
			}
			return flag;
		}
		return false;
	}

	/**
	 * 获取根目录下拉框
	 * 
	 * @param selected
	 * @return
	 */
	public String selectMenu(Integer selected) {
		List<SysMenu> list = sm.findByWhere("where status = 1 and parent_id = 0 order by sort");
		StringBuffer sb = new StringBuffer();
		for (SysMenu menu : list) {
			sb.append("<option value=\"");
			sb.append(menu.getId());
			sb.append("\" ");
			if (selected != null) {
				sb.append(menu.getInt("id") == selected ? "selected" : "");
			}
			sb.append(">");
			sb.append(menu.getName());
			sb.append("</option>");
		}
		return sb.toString();
	}

	/**
	 * 获取父节点名称
	 * 
	 * @param model
	 * @return
	 */
	public String getParentName(SysMenu model) {
		Integer parentid = model.getParentId();
		if (parentid == null || parentid == 0) {
			return "根目录";
		}
		String parentName = sm.findById(model.getParentId()).getName();
		return parentName;
	}

	/**
	 * 获取角色菜单权限
	 * @param rid
	 * @return
	 */
	public String getTreeList() {
		List<SysMenu> list = sm.findByWhere("where status=? order by sort", 1);
		// 转指定格式map
		List<Map<String, Object>> treeList = FastList.newInstance();
		for (SysMenu item : list) {
			Map<String, Object> temp = FastMap.newInstance();
			temp.put("id", item.getId());
			temp.put("title", item.getName());
			temp.put("pId", item.getParentId());
			temp.put("spread", true);
			treeList.add(temp);
		}
		// 组装tree
		List<Map<String, Object>> roots = FastList.newInstance();
		for (Map<String, Object> item : treeList) {
			if (item.get("pId").equals(0)) {
				roots.add(findChildren(item, treeList));
			}
		}
		return JSON.toJSONString(roots);
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> findChildren(Map<String, Object> menu, List<Map<String, Object>> menuList) {
		for (Map<String, Object> item : menuList) {
			if (menu.get("id").equals(item.get("pId"))) {
				if (StrUtils.empty(menu.get("children"))) {
					List<Map<String, Object>> tempList = FastList.newInstance();
					menu.put("children", tempList);
				}
				List<Map<String, Object>> clist = (List<Map<String, Object>>) menu.get("children");
				clist.add(findChildren(item, menuList));
				menu.put("children", clist);
				if (clist.size() > 0) {
					menu.remove("checked");
				}
			}
		}
		return menu;
	}

	/**
	 * 获取没有权限的菜单
	 * 
	 * @param map
	 *            可以访问的菜单
	 * @return
	 */
	public List<SysMenu> getNoAuthMap(Map<Integer, List<SysMenu>> map) {
		List<SysMenu> list = sm.findAll();
		List<SysMenu> returnList = FastList.newInstance();
		if(!StrUtils.empty(map)){
			List<Integer> idList = FastList.newInstance();
			for (Integer key : map.keySet()) {
				List<SysMenu> childList = map.get(key);
				for (SysMenu sysMenu : childList) {
					idList.add(sysMenu.getInt("id"));
				}
				idList.add(key);
			}
			for (SysMenu sysMenu : list) {
				if (!idList.contains(sysMenu.getInt("id"))) {
					returnList.add(sysMenu);
				}
			}
		}
		return returnList;
	}

	/**
	 * 返回菜单权限
	 * 
	 * @param user
	 * @return
	 */
	public Map<Integer, List<SysMenu>> getAuthMap(SysUser user) {
		String menuids = "select menu_id from " + SysRoleMenu.tableName + " where role_id in" + " (select role_id from "
				+ SysUserRole.tableName + " where user_id = ?) group by menu_id";
		// 管理员
		if (user.getUserType() == 1) {
			menuids = "select id from " + SysMenu.tableName + " where -1 != ?"; // 所有菜单
		}
		Integer userid = user.getId();
		Map<Integer, List<SysMenu>> map = FastMap.newInstance();

		String sql = "where status=1 and parent_id=? and id in (" + menuids + ") order by sort";
		// 获取父级菜单
		List<SysMenu> rootList = sm.findByWhere(sql, 0, userid);
		if (rootList == null || rootList.size() == 0) {
			return null;
		}
		map.put(0, rootList);
		// 获取子级菜单
		for (SysMenu menu : rootList) {
			List<SysMenu> list = sm.findByWhere(sql, menu.getId(), userid);
			map.put(menu.getId(), list);
		}
		return map;
	}
}
